﻿/**
 * Created by Administrator on 2017/8/18 0018.
 */
var express = require('express');
var crypto = require("crypto");
var qr = require('qr-image')
var multer = require("multer");
var config = require('../../config.js');
var db = require('../../db/db.js');
var moment = require("moment");

var router = express.Router();
var goods_model = require('../../model/yoshop_goods.js');
var goods_spec_model = require('../../model/yoshop_goods_spec.js');
var goods_image_model = require("../../model/yoshop_goods_image");


var myutil = require("../../util/util");


router.post('/add', async function (req, res) {

    var data = req.body;
    data.create_time = new Date();
    data.sales_actual = 0;

    var obj = await goods_model.add(data);
    if (obj.code == 200) {
        var goods_id = obj.msg.insertId;



        var guigelist = JSON.parse(req.body.guigelist);
        for (var i = 0; i < guigelist.length; i++) {
            var guigeobj = guigelist[i];
            guigeobj.goods_id = goods_id;
            var ss = await goods_spec_model.add(guigeobj);
        }


        var imglist = req.body.imglist;
        if (typeof (imglist) != "undefined" && imglist != "") {
            imglist = JSON.parse(imglist);
            for (var i = 0; i < imglist.length; i++) {
                goods_image_model.add({ goods_id: goods_id, image_id: imglist[i].id, create_time: new Date() });
            }
        }



        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }


})


router.post("/edit", async function (req, res) {

    var data = req.body;
    var obj = await goods_model.edit(data);
    if (obj.code == 200) {


        // var imglist = req.body.imglist;
        // if (typeof (imglist) != "undefined" && imglist != "") {
        //     imglist = JSON.parse(imglist);
        //     for (var i = 0; i < imglist.length; i++) {
        //         var goods_image = await goods_image_model.getinfo("goods_id=" + req.body.id + " and image_id=" + imglist[i].id);
        //         if (goods_image.length == 0) {
        //             goods_image_model.add({ goods_id: req.body.id, image_id: imglist[i].id, create_time: new Date() });
        //         }
        //     }
        // }


        // var guigelist = JSON.parse(req.body.guigelist);
        // for (var i = 0; i < guigelist.length; i++) {
        //     var guigeobj = guigelist[i];
        //     var item = await goods_spec_model.getinfo("spec_value='" + guigeobj.spec_value + "' and goods_id='" + guigeobj.goods_id + "'");
        //     if (item.length == 0) {
        //         guigeobj.goods_id = req.body.id;
        //         var ss = await goods_spec_model.add(guigeobj);
        //     } else {
        //         var ss = await goods_spec_model.edit(guigeobj);
        //     }
        // }

        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})


router.post("/edit2", async function (req, res) {

    var data = req.body;
    var obj = await goods_model.edit(data);
    if (obj.code == 200) {

        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})


router.post('/list', async function (req, res) {
    console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", req.body);
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";
    var where1 = " 1=1 ";
    var join = "";
    var group = "";
    if (typeof (req.body.goods_name) != "undefined" && req.body.goods_name != "") {
        where = where + " and yoshop_goods.goods_name like  '%" + req.body.goods_name + "%'";
        where1 = where1 + " and yoshop_goods.goods_name like  '%" + req.body.goods_name + "%'";


    }
    if (typeof (req.body.isrecommend) != "undefined" && req.body.isrecommend != "") {
        where = where + " and yoshop_goods.isrecommend='" + req.body.isrecommend + "'";
        where1 = where1 + " and yoshop_goods.isrecommend='" + req.body.isrecommend + "'";

    }


    if (typeof (req.body.goods_status) != "undefined" && req.body.goods_status != "") {
        where = where + " and yoshop_goods.goods_status=" + req.body.goods_status;
        where1 = where1 + " and yoshop_goods.goods_status=" + req.body.goods_status;

    }
    if (typeof (req.body.code) != "undefined" && req.body.code != "") {
        where = where + " and yoshop_goods_spec.goods_no like  '%" + req.body.code + "%'";

        join = " join yoshop_goods_spec on yoshop_goods_spec.goods_id = yoshop_goods.id ";
        group = "  group by yoshop_goods.id ";

    }






    console.log("where", where);
    var list = await goods_model.getlist(rows, first, where, join, " order by yoshop_goods.id desc ", " yoshop_goods.*", group);
    for (var i = 0; i < list.length; i++) {
        var goods_spec = await goods_spec_model.getinfo("goods_id=" + list[i].id);
        var codelist = [];
        for (let j = 0; j < goods_spec.length; j++) {
            codelist.push(goods_spec[j].goods_no);
        }
        list[i].code = codelist.join("<br/>");

        if (goods_spec.length > 0) {
            list[i].goods_price = goods_spec[0].goods_price;
            list[i].line_price = goods_spec[0].line_price;
            list[i].stock_num = goods_spec[0].stock_num;
            list[i].goods_weight = goods_spec[0].goods_weight;
            list[i].spec_value = goods_spec[0].spec_value;

            list[i].goods_no = goods_spec[0].goods_no;


        }

     
     

        list[i].create_time = moment(list[i].create_time).format("YYYY-MM-DD HH:mm:ss");

        var goodlist = await db.query("select yoshop_upload_file.file_name from yoshop_goods_image join yoshop_upload_file on yoshop_upload_file.id=yoshop_goods_image.image_id  where yoshop_goods_image.goods_id=" + list[i].id
            + " order by yoshop_goods_image.seq asc ");
        if (goodlist.length > 0) {
            list[i].imgurl = goodlist[0].file_name;
        }
      



    }
    var count = await goods_model.getcount(where, join, " order by yoshop_goods.id desc ", " yoshop_goods.*", group);
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});


router.delete('/del', async function (req, res) {

    var where = " id in (" + req.body.ids + ")";
    var obj = await goods_model.del(where);
    if (obj.code == 200) {

        goods_spec_model.del("goods_id in (" + req.body.ids + ")");
        goods_image_model.del("goods_id in (" + req.body.ids + ")");

        goods_model.del(where);

        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});

router.post('/goods_spec/add', async function (req, res) {

    var data = req.body;
    var obj = await goods_spec_model.add(data);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }

});


router.post("/goods_spec/edit", async function (req, res) {

    var data = req.body;
    if (data.goods_sales == "") {
        data.goods_sales = 0;
    }
    var obj = await goods_spec_model.edit(data);
    if (obj.code == 200) {

        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "error"
        }
        res.jsonp(result);
    }

})


router.post('/goods_spec/del', async function (req, res) {

    var where = " id=" + req.body.id;
    var obj = await goods_spec_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});

router.post('/image/del', async function (req, res) {

    var where = " id=" + req.body.id;
    var obj = await goods_image_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});
router.post('/image/add', async function (req, res) {

    var imglist = JSON.parse(req.body.data);

    for (var i = 0; i < imglist.length; i++) {
        var obj = await goods_image_model.add({ goods_id: req.body.goodid, image_id: imglist[i].id, create_time: new Date() });
    }
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});





router.post('/info', async function (req, res) {

    var obj = await goods_model.getinfo("id=" + req.body.id);
    if (obj.length > 0) {
        var info = obj[0];


     

        var guigelist = await goods_spec_model.getinfo("goods_id=" + info.id);

        if (req.body.mid != undefined && req.body.mid != "") {
            for (var i = 0; i < guigelist.length; i++) {
                var goods = await goods_spec_model.getinfo("wxapp_id=0 and goods_no='" + guigelist[i].goods_no + "'");
                if (goods.length > 0) {
                    guigelist[i].yuanjia = goods[0].goods_price;
                }
            }
        }
        info.guigelist = guigelist;



        info.imglist = await db.query("select yoshop_upload_file.file_name,yoshop_goods_image.id  from yoshop_goods_image join yoshop_upload_file on yoshop_upload_file.id=yoshop_goods_image.image_id  where yoshop_goods_image.goods_id=" + info.id
            + " order by yoshop_goods_image.seq asc ");


        var result = {
            "status": "200",
            "message": "success",
            data: info
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


})


router.post('/updatestate', async function (req, res) {
    var obj = {};
    if (req.body.type == "recommend") {
        obj = await db.execute("update yoshop_goods set isrecommend=" + req.body.state + " where id in (" + req.body.ids + ")");
    } else if (req.body.type == "shard") {
        obj = await db.execute("update yoshop_goods set isshard=" + req.body.state + " where id in (" + req.body.ids + ")");
    }

    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});


router.post('/paixu', async function (req, res) {
    var data = JSON.parse(req.body.data);

    for (var i = 0; i < data.length; i++) {

        var id = data[i].id;
        var obj = await db.execute("update yoshop_goods_image set seq =" + i + " where id=" + id, []);

    }

    var result = {
        "status": "200",
        "message": "success"
    }
    res.jsonp(result);


});


router.post('/kucun', async function (req, res) {

    var shopconfig = myutil.getconfig();
    var where = " productdata.num < " + shopconfig.kucunnum;

    if (typeof (req.body.goods_name) != "undefined" && req.body.goods_name != "") {
        where = where + " and yoshop_goods.goods_name like  '%" + req.body.goods_name + "%'";



    }

    if (typeof (req.body.code) != "undefined" && req.body.code != "") {
        where = where + " and yoshop_goods_spec.goods_no like  '%" + req.body.code + "%'";

    }


    console.log("where", where);
    var list = await db.query("SELECT yoshop_goods_spec.*,productdata.num,yoshop_goods.category_id,yoshop_goods.goods_name FROM `productdata` join productgood on productgood.id = productdata.productid join yoshop_goods_spec on yoshop_goods_spec.goods_no = productgood.code join yoshop_goods on yoshop_goods.id=yoshop_goods_spec.goods_id  where "
        + where, []);
    for (var i = 0; i < list.length; i++) {



        var type = await category_model.getinfo("id=" + list[i].category_id);
        if (type.length > 0) {
            list[i].typename = type[0].name;
        }

    }


    res.send({ status: 200, data: list, message: "" });

});
router.post('/buhuo', async function (req, res) {


    var obj = await db.execute("update yoshop_goods_spec set stock_num=stock_num+" + req.body.stock_num + " where goods_no='" + req.body.code + "'", []);

    if (obj.code == 200) {

        var obj = await db.execute("update productdata set num=num-" + req.body.stock_num + " where productid=" + req.body.productid, []);


        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {

        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }



});



router.post('/goodscomment/list', async function (req, res) {
    console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", req.body);
    var page;
    var rows;
    if (isNaN(req.body.page)) {
        page = 1;
    } else {
        page = +req.body.page;
    }
    if (isNaN(req.body.rows)) {
        rows = 10;
    } else {
        rows = +req.body.rows;
    }
    var first = rows * (page - 1);

    var where = " 1=1 ";



    console.log("where", where);
    var list = await goodscomment_model.getlist(rows, first, where, "   join yoshop_order on yoshop_order.id = goodscomment.order_id  join yoshop_user on yoshop_user.user_id = goodscomment.user_id ", " order by goodscomment.id desc ",
        " goodscomment.*,yoshop_order.order_no,yoshop_user.nickname,yoshop_user.avatarurl", "  ");
    for (var i = 0; i < list.length; i++) {
        var goods_spec = await goods_spec_model.getinfo("goods_id=" + list[i].id);
        var codelist = [];
        for (let j = 0; j < goods_spec.length; j++) {
            codelist.push(goods_spec[j].goods_no);
        }
        list[i].code = codelist.join("<br/>");


        list[i].createtime = moment(list[i].createtime).format("YYYY-MM-DD HH:mm:ss");



    }
    var count = await goodscomment_model.getcount(where, "   join yoshop_order on yoshop_order.id = goodscomment.order_id  join yoshop_user on yoshop_user.user_id = goodscomment.user_id ");
    var allcount = parseInt(parseInt(count) / rows) + 1;
    if (count % rows == 0) {
        allcount = allcount - 1;
    }

    res.send({ status: 200, data: list, message: "", allcount: allcount, count: count });

});

router.post('/goodscomment/del', async function (req, res) {

    var where = " id=" + req.body.id;
    var obj = await goodscomment_model.del(where);
    if (obj.code == 200) {
        var result = {
            "status": "200",
            "message": "success"
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "success"
        }
        res.jsonp(result);
    }


});

module.exports = router;   /*暴露这个 router模块*/